#include "ringbuffer.h"

void ringbuffer_init(ringbuffer_t *rb, uint8_t *buffer, uint32_t size)
{
	if (!rb) return ;
	
	rb->buffer = buffer;
	rb->size = size;
	rb->len = 0;
	rb->header = rb->buffer;
	rb->tail = rb->buffer;
}

inline uint32_t ringbuffer_push(ringbuffer_t *rb, uint8_t *data, uint32_t len)
{
	if (!rb || !data || 0 == len) return 0;
	
	int i;
	for (i = 0; i < len; i++) {
		if (rb->len == rb->size) {
			break;
		}
		
		rb->header[0] = data[i];
		++rb->header;
		++rb->len;
		
		if (rb->header == rb->buffer + rb->size) {
			rb->header = rb->buffer;
		}
	}
	
	return i;
}

uint32_t ringbuffer_pop(ringbuffer_t *rb, uint8_t *data, uint32_t len)
{
	if (!rb || !data || 0 == len) return 0;
	
	int i = 0;
	for (i = 0; i < len; i++) {
		if (0 == rb->len) {
			break;
		}
		
		data[i] = rb->tail[0];
		++rb->tail;
		--rb->len;
		
		if (rb->tail == rb->buffer + rb->size) {
			rb->tail = rb->buffer;
		}
	}
	
	return i;
}

bool ringbuffer_is_empty(ringbuffer_t *rb)
{
	return (!rb || 0 == rb->len); 
}

uint32_t ringbuffer_get_len(ringbuffer_t *rb)
{
	if (!rb) return 0;
	
	return rb->len;
}

bool ringbuffer_is_full(ringbuffer_t *rb)
{
    if (!rb) return false;

    return (rb->len == rb->size);
}


